package com.example.tcpudptool;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    private boolean isTcpConnected = false;
    private boolean isUdpConnected = false;
    private Thread tcpThreadClient = null;
    private Thread tcpThreadServer = null;
    private Thread udpThread = null;
    private EditText ipTextEdit; // IP的编辑栏
    private EditText recTextEdit;
    private EditText sendTextEdit;
    private TextView statusText; // 左上角状态信息
    private Button createTcpButton;
    private Button createUdpButton;
    private Button sendUdpButton;
    private Button sendTcpButton;

    static BufferedReader tcpServerBufferedReader = null;
    static PrintWriter tcpServerPrintWriter = null;
    static BufferedReader tcpClientBufferedReader = null;
    static PrintWriter tcpClientPrintWriter = null;
    private String recvMessageClient = "";
    private char connectFlag = 0;
    private Vibrator vibrator;
    private char[] charBuff;

    private DatagramSocket udpSocket;
    private DatagramPacket udpRecPack;
    private DatagramPacket udpSendPack;
    private Socket tcpSocketClient = null;
    private byte[] recvUdpBuf;
    private ServerSocket server;
    private Socket serversSocket;
    private char[] serverRecCharBuff;

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);// 全屏设置

        createTcpButton = (Button) findViewById(R.id.createTcpButt);
        sendTcpButton = (Button) findViewById(R.id.sendTcpButt);
        sendUdpButton = (Button) findViewById(R.id.sendUdpButt);
        createUdpButton = (Button) findViewById(R.id.createUdpButt);
        recTextEdit = (EditText) findViewById(R.id.editTextRec);
        sendTextEdit = (EditText) findViewById(R.id.editTextSend);
        ipTextEdit = (EditText) findViewById(R.id.editTextIP);
        statusText = (TextView) findViewById(R.id.textStatus);
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);

        ipTextEdit.setText("192.168.1.100:5006");
        sendTextEdit.setText("Hello world");
        sendTcpButton.setEnabled(false);
        sendUdpButton.setEnabled(false);
    }

    /**
     * @description butt清空接收框
     * 
     * @param source
     */
    public void clickedClear(View source) {
        vibrator.vibrate(40);
        recTextEdit.setText("");
    }

    /**
     * @description butt tcp发送
     * 
     * @param source
     */
    public void clickedTcpSend(View source) {
        vibrator.vibrate(20); // 震动20ms
        if (isTcpConnected == true && connectFlag == 1) {
            tcpClientPrintWriter.print(sendTextEdit.getText().toString());// 把里面的内容放入发送缓冲区
            tcpClientPrintWriter.flush(); // 发送缓冲区的东西
        }
    }

    /**
     * @description butt udp连接建立
     * 
     * @param source
     */
    public void clickedUdpCreate(View source) {
        vibrator.vibrate(20); // 震动20ms
        if (!isUdpConnected) {
            try {
                recvUdpBuf = new byte[100];
                udpSocket = new DatagramSocket(this.getCurrentPort());
                udpRecPack = new DatagramPacket(recvUdpBuf, recvUdpBuf.length);
                String sendStr = sendTextEdit.getText().toString();
                udpSendPack = new DatagramPacket(sendStr.getBytes(), sendStr.getBytes().length,
                        InetAddress.getByName(this.getCurrentIP()), this.getCurrentPort());
                createUdpButton.setText("断开Udp");
                isUdpConnected = true;
                sendUdpButton.setEnabled(true);
                statusText.setText("连接成功!");
            } catch (IOException e) {
                e.printStackTrace();
                statusText.setText("连接失败!");
                vibrator.vibrate(400);

            }

            udpThread = new Thread() {
                public void run() {
                    while (true) {
                        try {
                            udpSocket.receive(udpRecPack);
                            if (recvUdpBuf[0] != 0) {
                                Message msg = new Message();
                                msg.what = 3;
                                mHandler.sendMessage(msg);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            udpThread.start();
        } else {
            isUdpConnected = false;
            sendUdpButton.setEnabled(false);
            udpThread.interrupt();
            if (udpSocket != null)
                udpSocket.close();
            createUdpButton.setText("Udp连接");
        }
    }

    /**
     * @description butt udp发送
     * 
     * @param source
     */
    public void clickedUdpSend(View source) {
        vibrator.vibrate(20); // 震动20ms
        if (isUdpConnected) {
            new Thread() {
                public void run() {
                    try {
                        // 设置data就行, data长度无需设置
                        udpSendPack.setData(sendTextEdit.getText().toString().getBytes());
                        udpSocket.send(udpSendPack);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }

    }

    /**
     * @description
     * 
     * @param sourve
     */
    public void clickedCreateTcpServer(View sourve) {
        tcpThreadServer = new Thread() {
            @Override
            public void run() {
                serverRecCharBuff = new char[500];
                try {
                    server = new ServerSocket(MainActivity.this.getCurrentPort());
                    serversSocket = server.accept();
                    tcpServerBufferedReader = new BufferedReader(new InputStreamReader(serversSocket.getInputStream()));
                    tcpServerPrintWriter = new PrintWriter(serversSocket.getOutputStream());
                    while (true) {
                        tcpServerBufferedReader.read(serverRecCharBuff);
                        if (serverRecCharBuff[0] != 0) {
                            Message msg = new Message();
                            msg.what = 4;
                            mHandler.sendMessage(msg);
                        }

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        };
        tcpThreadServer.start();

    }

    public void clickedTcpServerSend(View sourve) {
        vibrator.vibrate(40);
        new Thread() {
            public void run() {
                tcpServerPrintWriter.print(sendTextEdit.getText().toString());
                tcpServerPrintWriter.flush();
            }
        }.start();
    }

    /**
     * @description butt tcpClient建立连接
     * 
     * @param sourve
     */
    public void clickedCreateTcp(View sourve) {
        if (isTcpConnected) // 连接的时候按下这个按钮时,行为是关闭socket连接.因为此时按钮的功能为"停止连接"
        {
            isTcpConnected = false;
            try {
                if (tcpSocketClient != null) {// 关闭socket连接
                    tcpSocketClient.close();
                    tcpSocketClient = null;
                    tcpClientPrintWriter.close();
                    tcpClientPrintWriter = null;
                }
            } catch (IOException e) {
                e.printStackTrace(); // 深度的调试信息
            }
            tcpThreadClient.interrupt();
            createTcpButton.setText("TCP连接"); // "停止连接"按钮切换为"开始连接"
            ipTextEdit.setEnabled(true);
        } else // 因为程序的isTcpConnected初始值为false,所以第一次执行会先进入else的程序,而且此时按钮的功能为"开始连接"
        {
            isTcpConnected = true;
            createTcpButton.setText("断开TCP"); // "开始连接"按钮切换到"停止连接"
            sendTcpButton.setEnabled(true);
            ipTextEdit.setEnabled(false);
            tcpThreadClient = new Thread(mRunnable); // new出一个wifi线程
            tcpThreadClient.start(); // 开启线程
        }
    }

    // 线程:建立WiFi连接，监听服务器发来的消息-------------------wifi连接的核心部分
    private Runnable mRunnable = new Runnable() {
        public void run() {

            String sIP = getCurrentIP();
            if (sIP == null)
                return;
            int port = getCurrentPort();
            if (port == 0)
                return;
            Log.d("gjz", "IP:" + sIP + ":" + port);

            try {
                // 连接服务器
                tcpSocketClient = new Socket(sIP, port); // Port_num
                // 取得输入、输出流
                tcpClientBufferedReader = new BufferedReader(new InputStreamReader(tcpSocketClient.getInputStream())); // socket读的核心语句,
                // 绑定输入流
                tcpClientPrintWriter = new PrintWriter(tcpSocketClient.getOutputStream(), true); // socket写的核心语句,tcpClientPrintWriter输出流与socket的输出流绑定
                recvMessageClient = "连接成功!";// 消息
                connectFlag = 1; // 连接成功标志立起来
                vibrator.vibrate(50);
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            } catch (Exception e) {
                recvMessageClient = "IP错误!";// 消息
                connectFlag = 0; // 连接标志置0
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
                return;
            }
            charBuff = new char[500];
            while (isTcpConnected) // 已连接上,等待收发行动
            {
                try {
                    tcpClientBufferedReader.read(charBuff);
                    if (charBuff[0] != 0) {
                        Message msg = new Message();
                        msg.what = 2;
                        mHandler.sendMessage(msg);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    };

    Handler mHandler = new Handler() { // 处理来自mRunnable线程的信息
        public void handleMessage(Message msg) { // 来自mHandler.sendMessage(msg)的信息
            super.handleMessage(msg);
            if (msg.what == 0) {
            } else if (msg.what == 1) {
                if (recvMessageClient == "IP空!" || recvMessageClient == "IP错误!") {
                    vibrator.vibrate(500);
                } else if (recvMessageClient == "连接成功!") {
                }
                statusText.setText(recvMessageClient); // 刷新消息
            } else if (msg.what == 2) {
                recTextEdit.append(String.valueOf(charBuff));
                charBuff[0] = 0;
            } else if (msg.what == 3) {
                recTextEdit.append(new String(recvUdpBuf));
                recvUdpBuf[0] = 0;
            } else if (msg.what == 4) {
                recTextEdit.append(new String(serverRecCharBuff));
                serverRecCharBuff[0] = 0;
            }
        }
    };

    /**
     * @description 截取ip输入框的ip
     * 
     * @return
     */
    private String getCurrentIP() {
        String msgText = ipTextEdit.getText().toString();
        if (msgText.length() == 0) {
            recvMessageClient = "IP空!";// 消息
            Message msg = new Message();
            msg.what = 1;
            mHandler.sendMessage(msg);
            return null;
        }
        int start = msgText.indexOf(":"); // 返回一个字符在字符串的位置
        if ((start == -1) || (start + 1 >= msgText.length())) {
            recvMessageClient = "IP非法!";// 消息
            Message msg = new Message();
            msg.what = 1;
            mHandler.sendMessage(msg);
            return null;
        }
        String sIP = msgText.substring(0, start); // 截取 >=0 且 <start位置 的字符串
        return sIP;
    }

    /**
     * @description 截取ip输入框的port
     * 
     * @return
     */
    private int getCurrentPort() {
        String msgText = ipTextEdit.getText().toString();
        if (msgText.length() == 0) {
            recvMessageClient = "IP空!";// 消息
            Message msg = new Message();
            msg.what = 1;
            mHandler.sendMessage(msg);
            return 0;
        }
        int start = msgText.indexOf(":"); // 返回一个字符在字符串的位置
        if ((start == -1) || (start + 1 >= msgText.length())) {
            recvMessageClient = "IP非法!";// 消息
            Message msg = new Message();
            msg.what = 1;
            mHandler.sendMessage(msg);
            return 0;
        }
        String sPort = msgText.substring(start + 1); // 截取 start+1位置及后面的字符串
        int port = Integer.parseInt(sPort); // String 转 int
        return port;
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onDestroy()
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isTcpConnected) {
            isTcpConnected = false;
            try {
                if (tcpSocketClient != null) {
                    tcpSocketClient.close();
                    tcpSocketClient = null;
                    tcpClientPrintWriter.close();
                    tcpClientPrintWriter = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            tcpThreadClient.interrupt(); // 退出阻塞的状态
            connectFlag = 0; // 连接上的标志清零
        }

    }
}